package com.nidu.demo.common.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class InEnumValidator implements ConstraintValidator<InEnum, Integer> {

    private List<Integer> validValues;

    @Override
    public void initialize(InEnum annotation) {
        IntArrayValuable[] values = annotation.value().getEnumConstants();
        if (values.length == 0) {
            this.validValues = new ArrayList<>();
        } else {
            this.validValues = Arrays.stream(values[0].array()).boxed().collect(Collectors.toList());
        }
    }


    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        // 允许 null 值，避免不必要的校验
        if (value == null) {
            return true;
        }
        if (validValues.contains(value)) {
            return true;
        }
        // 自定义错误信息
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(
                String.format("值 %d 不在枚举范围内: %s", value, validValues)
        ).addConstraintViolation();
        return false;
    }
}
